package com.cn.gxa.springmongo.service;

import com.cn.gxa.springmongo.pojo.Post;
import com.mongodb.client.result.DeleteResult;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PostService {
    @Autowired
    private MongoTemplate  mongoTemplate;


    public  int  add(Post post){
        post.setCreatTime(new  Date());
        post.setUpdateTime(new  Date());
        post=mongoTemplate.save(post);
        System.out.println(post);
        return  post==null?0:1;
    }

    public  int  del(Post post){
        DeleteResult deleteResult=  mongoTemplate.remove(post);
        return   1;
    }

    public  int  delById(Integer  no){
        //查询条件
        Query query=new Query(Criteria.where("no").is(no));
        //执行查询
        //mongoTemplate.remove(mongoTemplate.findOne(query, Post.class));
        mongoTemplate.remove(query,Post.class);
        return   1;
    }
    public  int  delBy_id(String  id){//MongoDB 自己生成的id  唯一
        //查询条件
        Query query=new Query(Criteria.where("_id").is(id));
        //执行查询
        mongoTemplate.remove(query,Post.class);
        return   1;
    }

    /**
     * 查询该用户所以的帖子
     * @param userId
     * @return
     */
    public List<Post> findByUserId(Integer  userId){
        //查询条件
        Query query=new Query(Criteria.where("userId").is(userId));
        //执行查询
        List<Post> list=mongoTemplate.find(query,Post.class);
        return  list;
    }


    public  int  update(Post post){
        Query query=new Query(Criteria.where("no").is(post.getNo()));
        Update update=new Update()
                .set("title",post.getTitle())
                .set("context",post.getContext())
                .set("state",1)
                .set("updateTime",new Date());
        mongoTemplate.updateFirst(query,update,Post.class);
        return  1;

    }

}
